<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script type="text/javascript">
        function WebSocketTest()
        {
            if ("WebSocket" in window)
            {


                // 打开一个 web socket
                var user=document.getElementById("user").value;

                ws = new WebSocket("ws://"+location.host+"/humiture/"+user);

                ws.onopen = function()
                {
                    // Web Socket 已连接上，使用 send() 方法发送数据
                   // ws.send("发送数据");
                   fillData("连接建立")
                };

                ws.onmessage = function (evt)
                {
                    var received_msg = evt.data;
                    fillData(received_msg);
                };

                ws.onclose = function()
                {
                    // 关闭 websocket
                    fillData("连接关闭")
                };
            }

            else
            {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        }

        function sendData() {
            var toUser=document.getElementById("toUser").value;
            var msg=document.getElementById("msg").value;
            var message='{"humidity":"'+toUser+'","temperature":"'+msg+'"}'
            ws.send(message);
        }



        function fillData(data) {
            document.getElementById("content").innerHTML = data;
        }

        function closews() {
            ws.close();
        }
    </script>
</head>
<body>
用户名:<input id="user"> <button onclick="WebSocketTest()">连接</button><br>
收消息的人:<input id="toUser"> <br>
内容:<textarea id="msg"></textarea><button onclick="sendData()">发送</button><br>
<br>
<button onclick="closews()">关闭</button><br>
<br>
<br>
<br>

<span id="content"></span>
</body>
</html>